﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FbKPI.Model;
using FbKPI.Facade;
using FbKPI.Facade.Validator;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Web.Script.Services;
using System.Transactions;
using System.IO;

namespace FBKPI.ProcessRequest
{
    /// <summary>
    /// Summary description for KPIAchievementHandler
    /// </summary>
    public class KPIAchievementHandler : IHttpHandler
    {
        private sysLogFacade sysLogFacade = new sysLogFacade();
        private sysLog objSysLog = new sysLog();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string msg = "OK";
            if (HttpContext.Current.Request.Files.Count > 0)
            {
                msg = this.Save();
            }
            else
            {
                msg = this.SaveNoAttachment();
            }
            ////this.Save();
            context.Response.Write(msg);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Save()
        {
            string msg = "OK";
            var data = HttpContext.Current.Request.Form;
            var User = HttpContext.Current.Server.UrlDecode(data["CurrUser"]);
            Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(User));
            try
            {
               
                var KPIAssignID = HttpContext.Current.Server.UrlDecode(data["KPIAssignID"]);
                var KPIAssignDetailID = HttpContext.Current.Server.UrlDecode(data["KPIAssignDetailID"]);
                var KPIId = HttpContext.Current.Server.UrlDecode(data["KPIId"]);
                var Year = HttpContext.Current.Server.UrlDecode(data["Year"]);
                var Status = HttpContext.Current.Server.UrlDecode(data["Status"]);
                var MethodDtlId = HttpContext.Current.Server.UrlDecode(data["MethodDtlId"]);
                var Realization = HttpContext.Current.Server.UrlDecode(data["Realization"]);
                var isLock = HttpContext.Current.Server.UrlDecode(data["isLock"]);
                var Score = HttpContext.Current.Server.UrlDecode(data["Score"]);
                var FileNameImages = HttpContext.Current.Server.UrlDecode(data["FileName"]);
                var DeleteAttachment = HttpContext.Current.Server.UrlDecode(data["DeleteAttachment"]);

                KPIAchievementFacade Af = new KPIAchievementFacade();
                List<KPIAchievement> list = new List<KPIAchievement>();
                KPIAchievement obj = new KPIAchievement();

                string[] ArrMethodDtlId = MethodDtlId.Split('|');
                string[] ArrRealization = Realization.Split('|');
                string[] ArrisLock = isLock.Split('|');
                string[] ArrScore = Score.Split('|');

                for (int i = 0; i < ArrMethodDtlId.Length - 1; i++)
                {
                    if (ArrMethodDtlId[i].ToString().Trim() != "undefined")
                    {
                        obj = new KPIAchievement();
                        obj.ID = 0;
                        obj.KPIAssign.ID = Convert.ToInt32(KPIAssignID);
                        obj.Year = Convert.ToInt32(Year);
                        obj.isActive = true;
                        obj.isLocked = ArrisLock[i].ToString() == "1" ? true : false;
                        obj.CreateBy = CurrUser.Email;
                        obj.Realization = ArrRealization[i].ToString();
                        obj.MethodDtlId = Convert.ToInt32(ArrMethodDtlId[i].ToString());
                        obj.Score = ArrScore[i].ToString();
                        obj.StatusByUser.ID = Convert.ToInt32(Status);
                        obj.LastModifiedBy = CurrUser.Email;

                        list.Add(obj);
                    }

                }

                KPIAttachment objAttachment = new KPIAttachment();
                List<KPIAttachment> listAttachment = new List<KPIAttachment>();


                if (HttpContext.Current.Request.Files.Count > 0)
                {
                    objAttachment.ID = 0;
                    objAttachment.KPI.ID = Convert.ToInt32(KPIId);
                    objAttachment.KPIAssign.ID = Convert.ToInt32(KPIAssignID);
                    objAttachment.KPIAssignDetail.ID = Convert.ToInt32(KPIAssignDetailID);
                    objAttachment.CreateBy = CurrUser.Email;
                    objAttachment.isActive = true;

                    HttpPostedFile hpf = HttpContext.Current.Request.Files[0] as HttpPostedFile;

                    //var file = HttpContext.Current.Request.Files[0];
                    string FileName = string.Empty;
                    if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                    {
                        string[] files = hpf.FileName.Split(new char[] { '\\' });
                        FileName = files[files.Length - 1];
                    }
                    else
                    {
                        FileName = hpf.FileName;

                        if (hpf.ContentType.Trim().ToLower().Contains("image"))
                        {

                            FileName = FileNameImages;
                        }
                    }

                    objAttachment.DocumentFileName = FileName;

                    byte[] datas = new byte[hpf.ContentLength];
                    hpf.InputStream.Position = 0;
                    hpf.InputStream.Read(datas, 0, hpf.ContentLength);


                    string path = HttpContext.Current.Server.MapPath("~/Attachment/AttachmantAchievmentKPI/" + objAttachment.KPI.ID.ToString() + "/" + objAttachment.KPIAssign.ID.ToString() + "/" + objAttachment.KPIAssignDetail.ID.ToString());
                    if (!System.IO.Directory.Exists(path))
                        System.IO.Directory.CreateDirectory(path);


                    objAttachment.DocumentNotes = "/Attachment/AttachmantAchievmentKPI/" + objAttachment.KPI.ID.ToString() + "/" + objAttachment.KPIAssign.ID.ToString() + "/" + objAttachment.KPIAssignDetail.ID.ToString() + "/" + FileName;

                    FileName = System.IO.Path.Combine(path, FileName);
                    if (System.IO.File.Exists(FileName))
                        System.IO.File.Delete(FileName);

                    hpf.SaveAs(FileName);

                    hpf.InputStream.Close();
                    hpf.InputStream.Dispose();

                    listAttachment.Add(objAttachment);
                }

                string[] ArrDeleteAttachment = DeleteAttachment.Split('|');
                List<KPIAttachment> listAttachmenDelete = new List<KPIAttachment>();
                KPIAttachment objDelete = new KPIAttachment();

                for (int i = 0; i < ArrDeleteAttachment.Length; i++)
                {
                    if (ArrDeleteAttachment[i].ToString().Trim() != "")
                    {
                        objDelete = new KPIAttachment();
                        objDelete.ID = Convert.ToInt32(ArrDeleteAttachment[i].Trim());
                        listAttachmenDelete.Add(objDelete);
                    }

                }


                //using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
                //{
                if (Af.Save(list, listAttachment, listAttachmenDelete))
                    msg = "Transaction Success";
                else
                    msg = "Transaction Failed";

                //trans.Complete();
                //trans.Dispose();
                //}

                //KPISendEmail objSendEmail = new KPISendEmail();
                //objSendEmail.KPIEmailAchievment(Convert.ToInt32(KPIId), CurrUser.FirstName);
                objSysLog.Description = "Achievement With Attachment kpi success !";
            }
            catch (Exception ex)
            {
                objSysLog.Description = ex.Message;
            }

            objSysLog.LogEvent = "Achievment KPI";
            objSysLog.Source = "KPIAchievementHandler.ashx";
            objSysLog.CreatedBy = CurrUser.Email;
            objSysLog.CreatedDate = DateTime.Now;

            sysLogFacade.Save(objSysLog);

            return msg;
        }

        private string SaveNoAttachment()
        {
            string msg = "OK";
            Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["CurrUser"]));

            try
            {
                int KPIAssignID = Convert.ToInt16(HttpContext.Current.Request.QueryString["KPIAssignID"]);
                int Year = Convert.ToInt16(HttpContext.Current.Request.QueryString["Year"]);
                int Status = Convert.ToInt16(HttpContext.Current.Request.QueryString["Status"]);
                string MethodDtlId = HttpContext.Current.Request.QueryString["MethodDtlId"];
                string Realization = HttpContext.Current.Request.QueryString["Realization"];
                string isLock = HttpContext.Current.Request.QueryString["isLock"];
                string Score = HttpContext.Current.Request.QueryString["Score"];
                string DeleteAttachment = HttpContext.Current.Request.QueryString["DeleteAttachment"];
                

                KPIAchievementFacade Af = new KPIAchievementFacade();
                List<KPIAchievement> list = new List<KPIAchievement>();
                KPIAchievement obj = new KPIAchievement();

                string[] ArrMethodDtlId = MethodDtlId.Split('|');
                string[] ArrRealization = Realization.Split('|');
                string[] ArrisLock = isLock.Split('|');
                string[] ArrScore = Score.Split('|');

                for (int i = 0; i < ArrMethodDtlId.Length - 1; i++)
                {
                    if (ArrMethodDtlId[i].ToString().Trim() != "undefined")
                    {
                        obj = new KPIAchievement();
                        obj.ID = 0;
                        obj.KPIAssign.ID = Convert.ToInt32(KPIAssignID);
                        obj.Year = Convert.ToInt32(Year);
                        obj.isActive = true;
                        obj.isLocked = ArrisLock[i].ToString() == "1" ? true : false;
                        obj.CreateBy = CurrUser.Email;
                        obj.Realization = ArrRealization[i].ToString();
                        obj.MethodDtlId = Convert.ToInt32(ArrMethodDtlId[i].ToString());
                        obj.Score = ArrScore[i].ToString();
                        obj.StatusByUser.ID = Convert.ToInt32(Status);
                        obj.LastModifiedBy = CurrUser.Email;


                        list.Add(obj);
                    }

                }

                string[] ArrDeleteAttachment = DeleteAttachment.Split('|');
                List<KPIAttachment> listAttachmenDelete = new List<KPIAttachment>();
                KPIAttachment objDelete = new KPIAttachment();

                for (int i = 0; i < ArrDeleteAttachment.Length; i++)
                {
                    if (ArrDeleteAttachment[i].ToString().Trim() != "")
                    {
                        objDelete = new KPIAttachment();
                        objDelete.ID = Convert.ToInt32(ArrDeleteAttachment[i].Trim());
                        listAttachmenDelete.Add(objDelete);
                    }

                }

                //using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
               // {
                    if (Af.SaveNoAttachment(list, listAttachmenDelete))
                        msg = "Transaction Success";
                    else
                        msg = "Transaction Failed";

                    //trans.Complete();
                    //trans.Dispose();
                //}

                    //KPISendEmail objSendEmail = new KPISendEmail();
                    //objSendEmail.KPIEmailAchievment(Convert.ToInt32(KPIId), CurrUser.FirstName);


              objSysLog.Description = "Achievement Without Attachment kpi success !";
            }
            catch (Exception ex)
            {
                objSysLog.Description = ex.Message;
            }

            objSysLog.LogEvent = "Achievment KPI";
            objSysLog.Source = "KPIAchievementHandler.ashx";
            objSysLog.CreatedBy = CurrUser.Email;
            objSysLog.CreatedDate = DateTime.Now;
            sysLogFacade.Save(objSysLog);

            return msg;
        }
    }
}